import os
import time
import requests

# Import QingLong notification module
try:
    from notify import send as ql_notify
    HAS_QL_NOTIFY = True
except ImportError:
    HAS_QL_NOTIFY = False

# Get cookies from environment variable
qqyd_data = os.getenv('qqyd_data')
if not qqyd_data:
    error_msg = "❌ QQ阅读签到失败: 环境变量 qqyd_data 未设置"
    print(error_msg)
    if HAS_QL_NOTIFY:
        ql_notify("QQ阅读签到通知", error_msg)
    raise ValueError(error_msg)

# Convert cookie string to dictionary
cookies = {}
for item in qqyd_data.split('; '):
    key, value = item.split('=', 1)
    cookies[key] = value

# Custom notification function for QQ阅读
def qqyd_notify(title, content):
    print(f"\n【QQ阅读通知】{title}\n{content}")
    if HAS_QL_NOTIFY:
        ql_notify(f"QQ阅读-{title}", content)

# Function to make requests and extract info
def make_request(url, headers, cookies, extract_fields, delay=0):
    time.sleep(delay)
    try:
        res = requests.get(url, headers=headers, cookies=cookies, timeout=10)
        data = res.json()
        
        # Special handling for video task response
        if "giveadreward" in url:
            if data.get("code") == -5:  # Already claimed reward
                return {
                    "message": "今日奖励已领取",
                    "revardMsg": "今日已获得过10赠币",
                    "status": "already_claimed"
                }
            elif data.get("code") == 0:  # Success
                return {
                    "message": data.get("message", "success"),
                    "revardMsg": data.get("revardMsg", "获得10赠币"),
                    "status": "success"
                }
        
        # Special handling for sign-in response
        if "sign" in url and data.get("code") == 0:
            return {
                "msg": "获得{}赠币".format(data.get("data", {}).get("signCount", 0)),
                "signCount": data.get("data", {}).get("signCount", 0),
                "status": "success"
            }
        
        # Default handling for other requests
        result = {field: data.get(field) for field in extract_fields}
        print("响应结果:", result)
        return result
    except Exception as e:
        error_msg = f"请求失败: {str(e)}"
        print(error_msg)
        return {"error": error_msg}

# Function to query account balance
def query_account(cookies):
    print("\n⏳ 正在查询账户余额...")
    url = "https://commontgw.reader.qq.com/h5/account"
    headers = {
        "Host": "commontgw.reader.qq.com",
        "Referer": "https://ih5.reader.qq.com/",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    result = make_request(url, headers, cookies, ['msg', 'balance', 'bookTicket'])
    
    if 'error' in result:
        return result
    
    balance_info = {
        "message": result.get('msg', '未知'),
        "阅币余额": result.get('balance', '未知'),
        "赠币余额": result.get('bookTicket', '未知')
    }
    return balance_info

# Collect all results for final notification
results = []

# First query account balance before tasks
initial_balance = query_account(cookies)
results.append(("初始余额查询", initial_balance))

# Task 1: Sign in
print("\n⏳ 正在执行QQ阅读签到任务...")
sign_url = "https://eventv3.reader.qq.com/activity/new_welfare/sign"
sign_headers = {
    "Host": "eventv3.reader.qq.com",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/109.0.5414.86 MQQBrowser/6.2 TBS/047823 Mobile Safari/537.36V1_AND_SQ_5.0.1 QQReader",
    "Origin": "https://ih5.reader.qq.com",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
}
sign_result = make_request(sign_url, sign_headers, cookies, ['msg', 'signCount'])
results.append(("签到", sign_result))

# Wait 10 seconds before next task
time.sleep(10)

# Task 2: Watch video for 10 coins
print("\n⏳ 正在执行观看视频任务...")
video_url = "https://commontgw.reader.qq.com/v7_6_6/giveadreward?adPositionId=18"
video_headers = {
    "Host": "commontgw.reader.qq.com",
    "Connection": "Keep-Alive",
    "Accept-Encoding": "gzip",
    "User-Agent": "okhttp/3.12.13"
}
video_result = make_request(video_url, video_headers, cookies, ['message', 'revardMsg'])
results.append(("观看视频", video_result))

# Wait 5 seconds before next task
time.sleep(10)

# Task 3: Watch ad videos for coins (run 3 times with 10s intervals)
print("\n⏳ 正在执行观看广告任务(3次)...")
ad_url = "https://eventv3.reader.qq.com/activity/new_welfare/receiveVideo?type=70526242"
ad_headers = {
    "Host": "eventv3.reader.qq.com",
    "sec-ch-ua": "\"Not)A;Brand\";v=\"99\", \"Android WebView\";v=\"127\", \"Chromium\";v=\"127\"",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/127.0.6533.103 Mobile Safari/537.36V1_AND_SQ_5.0.1 QQReader",
    "Referer": "https://ih5.reader.qq.com/",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
}

ad_results = []
for i in range(1):
    print(f"\n🔄 广告视频第{i+1}次尝试:")
    ad_result = make_request(ad_url, ad_headers, cookies, ['msg', 'data'], 60 if i > 0 else 0)
    ad_results.append(ad_result)
results.append(("观看广告", ad_results))

# Final query account balance after tasks
final_balance = query_account(cookies)
results.append(("最终余额查询", final_balance))

# Prepare final notification message
notification_msg = "📚 QQ阅读任务执行结果:\n\n"

# Add initial balance
notification_msg += f"【初始余额】\n"
if 'error' in initial_balance:
    notification_msg += f"  {initial_balance['error']}\n"
else:
    notification_msg += f"  状态: {initial_balance.get('message', '未知')}\n"
    notification_msg += f"  阅币: {initial_balance.get('阅币余额', '未知')}\n"
    notification_msg += f"  赠币: {initial_balance.get('赠币余额', '未知')}\n\n"

# Add tasks results
for task_name, result in results[1:-1]:  # Skip first and last which are balance queries
    if task_name == "观看广告":
        notification_msg += f"【{task_name}】\n"
        for i, res in enumerate(result, 1):
            if 'error' in res:
                notification_msg += f"  第{i}次: {res['error']}\n"
            else:
                notification_msg += f"  第{i}次: {res.get('msg', '未知')}, 获得赠币: {res.get('data', '未知')}\n"
    elif task_name == "观看视频":
        notification_msg += f"【{task_name}】"
        if isinstance(result, dict) and 'error' in result:
            notification_msg += f" {result['error']}\n"
        else:
            notification_msg += f" {result.get('message', '未知')}, {result.get('revardMsg', '未知')}\n"
    else:
        notification_msg += f"【{task_name}】"
        if isinstance(result, dict) and 'error' in result:
            notification_msg += f" {result['error']}\n"
        else:
            if task_name == "签到":
                notification_msg += f" {result.get('msg', '未知')}, 签到天数: {result.get('signCount', '未知')}\n"

# Add final balance
notification_msg += f"\n【最终余额】\n"
if 'error' in final_balance:
    notification_msg += f"  {final_balance['error']}\n"
else:
    notification_msg += f"  状态: {final_balance.get('message', '未知')}\n"
    notification_msg += f"  阅币: {final_balance.get('阅币余额', '未知')}\n"
    notification_msg += f"  赠币: {final_balance.get('赠币余额', '未知')}\n"

# Calculate balance changes
if 'error' not in initial_balance and 'error' not in final_balance:
    try:
        initial_yue = int(initial_balance.get('阅币余额', 0))
        final_yue = int(final_balance.get('阅币余额', 0))
        initial_zeng = int(initial_balance.get('赠币余额', 0))
        final_zeng = int(final_balance.get('赠币余额', 0))
        
        notification_msg += f"\n【余额变化】\n"
        notification_msg += f"  阅币变化: {final_yue - initial_yue}\n"
        notification_msg += f"  赠币变化: {final_zeng - initial_zeng}\n"
    except (ValueError, TypeError):
        notification_msg += f"\n【余额变化】\n  无法计算余额变化(数值转换错误)\n"

# Send final notification
qqyd_notify("任务完成", notification_msg)
print("\n✅ 所有任务已完成")